package cate.game.pvp.throne;

import cate.common.table.activity.throne.TBTrialChallengeRow;
import cate.common.table.d.GDFight;
import cate.common.table.d.GDOperation;
import cate.game.play.fighter.HeroFighter;
import cate.game.play.proce.play.PlayPO;
import cate.game.pvp.throne.data.trial.TBTrialReport;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.role.Role;
import cate.game.role.farm.AbstractFarmFTC;
import cate.game.role.pvp.throne.RoleTBTrial;
import cate.game.role.pvp.throne.msg.TBTrialChallengeResp;
import cate.game.role.pvp.throne.msg.TBTrialOpponentResp;

public class TBTrialFTC extends AbstractFarmFTC<RoleTBTrial> {

	private int level;

	private TBTrialChallengeRow row;

	@Override
	protected RoleTBTrial po(Role role) {
		return role.getPvp().throne.trial;
	}

	public TBTrialFTC(Role role, int level, TBTrialChallengeRow row) {
		setup(role);
		this.level = level;
		this.row = row;
	}

	@Override
	public void handleResult(Role role, PlayPO playPO) {
		super.handleResult(role, playPO);
		if (!role.getGame().pvp.throne.data.holder.base.timeTable.inTrial()) {
			role.sendNow(new TBTrialChallengeResp());
			return;
		}
		boolean win = playPO.winner == GDFight.Team.A;
		MixRes reward = new MixRes(role.getGame().table.throne.challengeRwd.getReward(win));
		int pointAdd = 0;
		role.getGame().facilities.getMongo().play.save(playPO);
		//记录日志 添加录像
		TBTrialReport report = new TBTrialReport();
		report.a = playPO.a.snapshot.base.copy();
		report.b = playPO.b.snapshot.base.copy();
		report.winner = playPO.winner;
		report.replayUid = playPO.uid;
		po(role).addReport(report);
		if (win) {
			pointAdd = (int) (row.getRwdPoint(level) * calCoeff(playPO));
			po(role).point += pointAdd;
			role.getGame().pvp.throne.message.trialSyncRank(role, playPO.a);
			report.point = pointAdd;
		}
		new MixResAdder().setRes(reward).setOperation(GDOperation.THRONE_TRIAL_CHALLENGE).exe(role);
		role.send(new TBTrialChallengeResp(win, reward, pointAdd));
		po(role).noticeUpdate();

		po(role).doRefresh();
		role.send(new TBTrialOpponentResp(po(role).lastRefreshTime, po(role).opponents));
	}

	private double calCoeff(PlayPO play) {
		double coeff1 = Math.max(Math.min((3.5 - play.rounds.size()) * 0.2, 0.5), 0);
		double damage = 0;
		double hurt = 0;
		for (HeroFighter allHero : play.teamEnd.a.getAllHero()) {
			damage += allHero.performance.damage;
			hurt += allHero.performance.hurt;
		}
		if (hurt <= 0d) {
			hurt = 1d;
		}
		double coeff2 = Math.max(Math.min((damage / hurt - 1) * 0.5, 0.5), 0);
		return 1 + coeff1 + coeff2;
	}
}
